
//
//  Created by xm on 2025/6/24.
//

#import "AncsProviderBleClient.h"
#import "AncsDefine.h"
#import <CoreBluetooth/CoreBluetooth.h>

@interface AncsProviderBleClient()<CBPeripheralManagerDelegate>

@property (nonatomic, strong) XMLogger *logger;
@property (strong, nonatomic) CBPeripheralManager *peripheralManager;
@property (strong, nonatomic) CBMutableService *customService;
@property (strong, nonatomic) CBCharacteristic *notificationCharacteristic;
@property (strong, nonatomic) CBCharacteristic *readCharacteristic;
@property (strong, nonatomic) CBCharacteristic *writeCharacteristic;

@property(nonatomic, strong) dispatch_queue_t bleDataSendQueue;



@end

@implementation AncsProviderBleClient


static NSString* Service_ID = NORMAL_Service_ID;
static NSString* Notify_Char_ID = NORMAL_Notify_Char_ID;
static NSString* Read_Char_ID = NORMAL_Read_Char_ID;
static NSString* Write_Char_ID = NORMAL_Write_Char_ID;
//static NSString* NACS_ServiceUUID = ANCS_Service_ID;
//static NSString* NotificationCharUUID = ANCS_Character_Notification_Source_ID;
//static NSString* ControlCharUUID = ANCS_Character_Control_Point_ID;
//static NSString* DataCharUUID = ANCS_Character_Control_Point_ID;



#pragma mark - getter
- (XMLogger *)logger
{
    if(!_logger){
        _logger = [XMLogger loggerWithScopeName:NSStringFromClass(self.class)];
    }
    
    return _logger;
}
- (dispatch_queue_t)bleDataSendQueue
{
    if(_bleDataSendQueue == nil){
        _bleDataSendQueue = dispatch_queue_create("YModemBleReceiver", DISPATCH_QUEUE_SERIAL);
    }
    
    return _bleDataSendQueue;
}



#pragma mark - api

-(void) start
{
    self.logger.log(@"start");
    self.peripheralManager = [[CBPeripheralManager alloc] initWithDelegate:self queue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
    
    [self watch];
    
}

-(void) sendData:(NSData*) data
{
//    self.logger.log(@"sendData");
    
    @weakify(self);
    dispatch_async(self.bleDataSendQueue, ^{
        @strongify(self);
        [self.peripheralManager updateValue:data forCharacteristic:self.notificationCharacteristic onSubscribedCentrals:nil];
    });

}
-(void) stop
{
    self.logger.log(@"stop");
    
    if(self.peripheralManager.isAdvertising){
        [self.peripheralManager stopAdvertising];
    }

    [self.peripheralManager removeAllServices];
    self.peripheralManager.delegate = nil;
    self.peripheralManager = nil;
}


#pragma mark - methods


-(void)watch
{
   
}

#pragma mark - CBPeripheralManagerDelegate

// 外设管理器状态更新回调
- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral {
    switch (peripheral.state) {
        case CBManagerStatePoweredOff:
            self.logger.log(@"蓝牙未开启");
            break;
        case CBManagerStateUnauthorized:
            self.logger.log(@"蓝牙未授权");
            break;
        case CBManagerStatePoweredOn:
            self.logger.log(@"蓝牙已开启");
            // 扫描特定服务的外设，这里使用一个示例UUID
            [self setupServiceAndCharacteristic];
            
            break;
            
        default:
            self.logger.log(@"蓝牙状态异常: %ld", (long)peripheral.state);
            break;
    }
}

// 配置服务和特征
- (void)setupServiceAndCharacteristic {
    self.logger.log(@"开启服务");
    // 创建一个可读写的特征
    self.notificationCharacteristic = [[CBMutableCharacteristic alloc] initWithType:[CBUUID UUIDWithString:Notify_Char_ID]
                                                                 properties:CBCharacteristicPropertyNotify
                                                                           value:nil
                                                                     permissions:CBAttributePermissionsReadable];
    
    self.readCharacteristic = [[CBMutableCharacteristic alloc] initWithType:[CBUUID UUIDWithString:Read_Char_ID]
                                                                 properties:CBCharacteristicPropertyRead
                                                                           value:nil
                                                                     permissions:CBAttributePermissionsReadable];
    
    self.writeCharacteristic = [[CBMutableCharacteristic alloc] initWithType:[CBUUID UUIDWithString:Write_Char_ID]
                                                                  properties:CBCharacteristicPropertyWrite
                                                                           value:nil
                                                                     permissions:CBAttributePermissionsWriteable];

    
    // 创建服务
    self.customService = [[CBMutableService alloc] initWithType:[CBUUID UUIDWithString:Service_ID] primary:YES];
    self.customService.characteristics = @[self.notificationCharacteristic, self.readCharacteristic, self.writeCharacteristic];
    
    // 添加服务到外设管理器
    [self.peripheralManager addService:self.customService];
}

// 添加服务完成回调
- (void)peripheralManager:(CBPeripheralManager *)peripheral didAddService:(CBService *)service error:(NSError *)error {
    if (error) {
        self.logger.log(@"添加服务失败: %@", error.localizedDescription);
        return;
    }
    
    self.logger.log(@"添加服务成功，开始广播");
    // 开始广播服务
    NSDictionary *advertisingData = @{
        CBAdvertisementDataLocalNameKey : @"VidoarrDemo", // 自定义外设名称
        CBAdvertisementDataServiceUUIDsKey : @[[CBUUID UUIDWithString:Service_ID]]
    };
    
    
    [self.peripheralManager startAdvertising:advertisingData];
}

// 开始广播回调
- (void)peripheralManagerDidStartAdvertising:(CBPeripheralManager *)peripheral error:(NSError *)error {
    if (error) {
        self.logger.log(@"开始广播失败: %@", error.localizedDescription);
        return;
    }
    
    self.logger.log(@"开始广播成功");
}

// 中心设备订阅特征回调
- (void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didSubscribeToCharacteristic:(CBCharacteristic *)characteristic {
    self.logger.log(@"中心设备订阅了特征 %@", characteristic.UUID.UUIDString);
    
 
}

- (void)peripheralManager:(CBPeripheralManager *)peripheral    didReceiveReadRequest:(CBATTRequest *)request {
    
//    NSData* receivedData = request.value;
//    NSString* json = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
    NSData* data = request.value;
    self.logger.log(@"收到读请求 data:%@", [AppHelper hexStringFromData:data]);
    
    
    [peripheral respondToRequest:request withResult:CBATTErrorSuccess];

    
 
}
- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveWriteRequests:(NSArray<CBATTRequest *> *)requests;
{
    [requests enumerateObjectsUsingBlock:^(CBATTRequest * _Nonnull request, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([request.characteristic.UUID isEqual:self.writeCharacteristic.UUID]) {
            
            NSData* data = request.value;
            self.logger.log(@"收到写请求 data:%@", [AppHelper hexStringFromData:data]);
            
            
      
            [peripheral respondToRequest:request withResult:CBATTErrorSuccess];
        }
    }];

}




@end
